<?php


namespace App\Modules\Admin\Services\System;


use App\Modules\Admin\Entities\System\DictDataModel;
use App\Modules\Admin\Services\BaseService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class DictDataService extends BaseService
{
    public function __construct(DictDataModel $dictModel)
    {
        $this->model = $dictModel;
    }
    public function lists(array $params) : array
    {
        $params['where_callback'] = function ($query) use ($params) {
            $request = request();
            if (!empty($dict_type = $request->input('dictType', ''))) {
                $query->where('dict_type',$dict_type);
            }
        };
        $lists = parent::lists($params);
        return $lists; // TODO: Change the autogenerated stub
    }
    public function create(array $params)
    {
        DB::beginTransaction();
        try{
            parent::create($params); // TODO: Change the autogenerated stub
            DB::commit();
            return true;
        }catch (Exception $e){
            DB::rollBack();
            return false;
        }
    }
    public function getSelect_Lists($request)
    {
        $type = $request->input('t', '');
        return $this->model->where(['dict_type'=>$type,'is_check'=>1])->get(['dict_label','dict_value','css_class','list_class'])->toArray();
    }

    public function getSelectLists($request)
    {
        $where['is_check'] = 1;
        $type = $request->input('t', '');
        if(Cache::has('sys_dict_data')){
           $sys_dict_data = Cache::get('sys_dict_data');
        }else {
            $sys_dict_data = [];
            $dict_list = $this->model->where($where)->get(['dict_label','dict_value','css_class','list_class','dict_type'])->toArray();
            foreach ($dict_list as $kay=>&$value){
                $sys_dict_data[$value['dict_type']][] = $value;
            }
            Cache::forever('sys_dict_data',$sys_dict_data);
        }
        return $sys_dict_data[$type];
    }
    public function getSelectListsArray($request)
    {
        $where['is_check'] = 0;
        $sys_dict_data = [];
        $dict_list = $this->model->where($where)->get(['dict_label','dict_value','css_class','list_class','dict_type'])->toArray();
        foreach ($dict_list as $kay=>&$value){
            $sys_dict_data[$value['dict_type']][] = $value;
        }
        Cache::forever('sys_dict_data',$sys_dict_data);

        return $sys_dict_data;
    }

    protected function tree_dict($data,$dict_type){

        $newarr = [];
        if ($data['dict_type'] == $dict_type) {
            $newarr[] = $data;
            $newarr = array_merge($newarr, $this->tree_dict($data,$dict_type));
        } else{
            $newarr[] = $data;
        }
        return $newarr;
    }

}
